package pl.edu.agh.dosgi.logging.tracker;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogListener;
import org.osgi.service.log.LogReaderService;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

import pl.edu.agh.dosgi.logging.util.LogReadersHolder;


@SuppressWarnings("rawtypes")
public class LogReaderTrackerCustomizer implements ServiceTrackerCustomizer {
	
	private BundleContext context;
	private LogListener logListener;
	private LogReadersHolder logReadersHolder;
	
	public LogReaderTrackerCustomizer(BundleContext context, LogListener logListener, LogReadersHolder logReadersHolder) {
		this.context = context;
		this.logListener = logListener;
		this.logReadersHolder = logReadersHolder;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Object addingService(ServiceReference reference) {
		LogReaderService logReaderService = context.getService(reference);
		
		logReaderService.addLogListener(logListener);
		logReadersHolder.addLogReader(logReaderService);
		
		return null;
	}

	@Override
	public void modifiedService(ServiceReference reference, Object service) {

	}

	@SuppressWarnings("unchecked")
	@Override
	public void removedService(ServiceReference reference, Object service) {
		LogReaderService logReaderService = context.getService(reference);
		
		logReaderService.removeLogListener(logListener);
		logReadersHolder.removeLogReader(logReaderService);
	}
}
